<!-- 图标搜索组件 -->
<template>
  <div class="icon-picker">
    <el-input v-model="search" placeholder="搜索图标">
      <template #append>
        <el-dropdown trigger="click" @command="handleCommand">
          <el-icon class="el-input__icon"><Upload /></el-icon>
          <template #dropdown>
            <el-scrollbar class="p-2">
              <el-dropdown-menu>
                <el-dropdown-item
                  v-for="(icon, index) in filteredIcons"
                  :key="index"
                  :command="icon"
                  style="border: 1px solid black"
                >
                  <!-- 注意这里的变化 -->
                  <div class="h-[15px] w-[15px]">
                    <component :is="getIconComponent(icon)" />
                  </div>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-scrollbar>
            <!-- 分页 -->
            <el-pagination
              :current-page="currentPage"
              :page-size="pageSize"
              :total="icons.length"
              layout="prev, pager, next"
              small
              @current-change="onPageChange"
            />
          </template>
        </el-dropdown>
      </template>
    </el-input>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';

import * as ElementPlusIconsVue from '@element-plus/icons-vue'; // 导入所有图标

// 单独导入 upload 图标用于输入框后缀
import { Upload } from '@element-plus/icons-vue';

const icons = Object.keys(ElementPlusIconsVue); // 获取所有图标名称
const search = ref(''); // 搜索条件
const currentPage = ref(1); // 当前页
const pageSize = ref(50); // 每页显示的图标数量

// 计算属性：根据搜索条件和分页计算出当前显示的图标
const filteredIcons = computed(() => {
  return icons
    .filter((icon) => icon.toLowerCase().includes(search.value.toLowerCase()))
    .slice(
      (currentPage.value - 1) * pageSize.value,
      currentPage.value * pageSize.value,
    );
});

// 确保 getIconComponent 返回的是 Vue 组件
function getIconComponent(name: string) {
  const IconComponent =
    ElementPlusIconsVue[name as keyof typeof ElementPlusIconsVue];
  if (!IconComponent) console.error(`Icon '${name}' not found.`);
  return IconComponent;
}

function handleCommand(command: string) {
  search.value = command; // 更新搜索框的值为选中的图标名称
  // console.log('Selected Icon:', command);
  // 在这里处理选择图标的逻辑
}

function onPageChange(page: number) {
  currentPage.value = page;
}
</script>

<style scoped>
.icon-picker {
  width: 100%;
}

.el-scrollbar {
  max-height: 200px; /* 调整为你的需求 */
  overflow: auto;
}

/* 使用 CSS Grid 布局来确保每行显示5个图标 */
.el-dropdown-menu {
  display: grid;
  grid-template-columns: repeat(5, 1fr); /* 每行5列 */
  gap: 8px; /* 设置间距 */
}

/* 设置图标的大小和对齐方式 */
.el-dropdown-item {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
